package blog.service.impl;

import blog.dao.NoticeDao;
import blog.pojo.Notice;
import blog.service.NoticeService;
import blog.util.Timestamp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeDao noticeDao;

    @Override
    public IPage<Notice> getPage(Integer page, Integer limit, Integer categoryId) throws Exception {
        Page<Notice> noticePage = new Page<>();
        noticePage.setSize(limit).setPages(page);
        QueryWrapper<Notice> wrapper = null;
        if(categoryId != null){
            wrapper = new QueryWrapper<>(new Notice().setCategoryId(categoryId));
        }
        return noticeDao.selectPage(noticePage, wrapper);
    }

    @Override
    public Page<Notice> getPage(Page page, Notice notice, String keywords) throws Exception {
        if (page == null) return null;
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>(notice)
                .ne("isuse", 2);
        if (keywords != null) {
            queryWrapper.and(Wrapper -> Wrapper.like("title", keywords).or().like("content", keywords));
        }
        return noticeDao.selectPage(page, queryWrapper);
    }

    @Override
    public Notice getInfo(Integer id) throws Exception {
        return noticeDao.selectOne(new QueryWrapper<Notice>().setEntity(new Notice().setId(id)));
    }

    @Override
    public Boolean update(Notice notice) throws Exception {
        notice.setGmtUpdate(Timestamp.gen());
        return noticeDao.updateById(notice) > 0;
    }

    @Override
    public Boolean insert(Notice notice) throws Exception {
        return noticeDao.insert(notice.setGmtCreate(Timestamp.gen()).setGmtUpdate(Timestamp.gen())) > 0;
    }
}
